<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 5.2.0">


  <link rel="apple-touch-icon" sizes="180x180" href="/murmur/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/murmur/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/murmur/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/murmur/images/logo.svg" color="#222">

<link rel="stylesheet" href="/murmur/css/main.css">



<link rel="stylesheet" href="//cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@5.15.1/css/all.min.css">
  <link rel="stylesheet" href="//cdn.jsdelivr.net/npm/animate.css@3.1.1/animate.min.css">
  <link rel="stylesheet" href="//cdn.jsdelivr.net/npm/nprogress@0.2.0/nprogress.css">
  <script src="//cdn.jsdelivr.net/npm/nprogress@0.2.0/nprogress.js"></script>

<script class="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"gitee.com","root":"/murmur/","scheme":"Gemini","version":"8.0.2","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12},"copycode":true,"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":"disqus","storage":true,"lazyload":false,"nav":null},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"fadeInDown","post_body":"fadeInDown","coll_header":"fadeInLeft","sidebar":"fadeInUp"}},"prism":false,"i18n":{"placeholder":"搜索...","empty":"没有找到任何搜索结果：${query}","hits_time":"找到 ${hits} 个搜索结果（用时 ${time} 毫秒）","hits":"找到 ${hits} 个搜索结果"}};
  </script>

  <meta name="description" content="除了Map，就是用Array存数据，老是要去重怎么办？">
<meta property="og:type" content="article">
<meta property="og:title" content="ES6 详解Set和WeakSet集合">
<meta property="og:url" content="https://gitee.com/lianghuilin/murmur.git/ecma_script/ES6%20%E8%AF%A6%E8%A7%A3Set%E5%92%8CWeakSet%E9%9B%86%E5%90%88/index.html">
<meta property="og:site_name" content="汇话板">
<meta property="og:description" content="除了Map，就是用Array存数据，老是要去重怎么办？">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2021-07-04T12:30:12.000Z">
<meta property="article:modified_time" content="2021-11-28T11:00:26.228Z">
<meta property="article:author" content="William Leung">
<meta name="twitter:card" content="summary">


<link rel="canonical" href="https://gitee.com/lianghuilin/murmur.git/ecma_script/ES6%20%E8%AF%A6%E8%A7%A3Set%E5%92%8CWeakSet%E9%9B%86%E5%90%88/">


<script class="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-CN'
  };
</script>

  <title>ES6 详解Set和WeakSet集合 | 汇话板</title>
  


  <script>
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?a49081c570a782a242cdf6e19e1a584d";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>




  <noscript>
  <style>
  body { margin-top: 2rem; }

  .use-motion .menu-item,
  .use-motion .sidebar,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header {
    visibility: visible;
  }

  .use-motion .header,
  .use-motion .site-brand-container .toggle,
  .use-motion .footer { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle,
  .use-motion .custom-logo-image {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line {
    transform: scaleX(1);
  }

  .search-pop-overlay, .sidebar-nav { display: none; }
  .sidebar-panel { display: block; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage" class="use-motion">
  <div class="headband"></div>

  <main class="main">
    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/murmur/" class="brand" rel="start">
      <i class="logo-line"></i>
      <h1 class="site-title">汇话板</h1>
      <i class="logo-line"></i>
    </a>
      <p class="site-subtitle" itemprop="description">设定目标，放慢步调，用温和的力量自我改革</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
    </div>
  </div>
</div>



<nav class="site-nav">
  <ul class="main-menu menu">
        <li class="menu-item menu-item-home">

    <a href="/murmur/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/murmur/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类</a>

  </li>
  </ul>
</nav>




</div>
        
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
  </div>

  <aside class="sidebar">

    <div class="sidebar-inner sidebar-nav-active sidebar-toc-active">
      <ul class="sidebar-nav">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <div class="sidebar-panel-container">
        <!--noindex-->
        <section class="post-toc-wrap sidebar-panel">
            <div class="post-toc animated"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#Set%E6%98%AF%E5%80%BC%E6%B0%B8%E4%B8%8D%E9%87%8D%E5%A4%8D%E7%9A%84%E7%89%B9%E6%AE%8A%E9%9B%86%E5%90%88"><span class="nav-number">1.</span> <span class="nav-text">Set是值永不重复的特殊集合</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Set%E9%9B%86%E5%90%88%E5%9F%BA%E7%A1%80API"><span class="nav-number">2.</span> <span class="nav-text">Set集合基础API</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#Set-prototype-constructor-%E6%9E%84%E9%80%A0%E5%87%BD%E6%95%B0%E5%88%9B%E5%BB%BA%E5%AE%9E%E4%BE%8B"><span class="nav-number">2.1.</span> <span class="nav-text">Set.prototype.constructor 构造函数创建实例</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Set-prototype-size%E5%B1%9E%E6%80%A7%E8%BF%94%E5%9B%9E%E5%85%83%E7%B4%A0%E7%9A%84%E4%B8%AA%E6%95%B0"><span class="nav-number">2.2.</span> <span class="nav-text">Set.prototype.size属性返回元素的个数</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Set-prototype-has-value-%E6%96%B9%E6%B3%95%E5%88%A4%E6%96%AD%E5%85%83%E7%B4%A0%E6%98%AF%E5%90%A6%E5%AD%98%E5%9C%A8"><span class="nav-number">2.3.</span> <span class="nav-text">Set.prototype.has(value) 方法判断元素是否存在</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%85%B3%E4%BA%8E%E5%94%AF%E4%B8%80%E5%80%BC%E7%9A%84%E5%88%A4%E6%96%AD"><span class="nav-number">2.4.</span> <span class="nav-text">关于唯一值的判断</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E8%B0%83%E7%94%A8Set-prototype-add-value-%E6%96%B9%E6%B3%95%EF%BC%8C%E5%90%91%E9%9B%86%E5%90%88%E8%BF%BD%E5%8A%A0%E6%95%B0%E6%8D%AE"><span class="nav-number">2.5.</span> <span class="nav-text">调用Set.prototype.add(value) 方法，向集合追加数据</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Set-prototype-delete-value-%E6%96%B9%E6%B3%95%E7%A7%BB%E9%99%A4%E5%85%83%E7%B4%A0"><span class="nav-number">2.6.</span> <span class="nav-text">Set.prototype.delete(value) 方法移除元素</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Set-prototype-clear-%E6%96%B9%E6%B3%95%E6%B8%85%E7%A9%BA%E9%9B%86%E5%90%88"><span class="nav-number">2.7.</span> <span class="nav-text">Set.prototype.clear() 方法清空集合</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Set%E9%9B%86%E5%90%88%E9%81%8D%E5%8E%86%E7%9A%843%E7%A7%8D%E6%96%B9%E5%BC%8F"><span class="nav-number">2.8.</span> <span class="nav-text">Set集合遍历的3种方式</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Set%E9%9B%86%E5%90%88%E6%A1%88%E4%BE%8B%E5%AE%9E%E8%B7%B5"><span class="nav-number">3.</span> <span class="nav-text">Set集合案例实践</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#Set%E9%9B%86%E5%90%88%E4%B8%8EArray%E6%95%B0%E7%BB%84%E4%B9%8B%E9%97%B4%E7%9A%84%E8%BD%AC%E6%8D%A2"><span class="nav-number">3.1.</span> <span class="nav-text">Set集合与Array数组之间的转换</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%8D%95%E4%B8%AA%E6%95%B0%E7%BB%84%E5%8E%BB%E9%87%8D"><span class="nav-number">3.2.</span> <span class="nav-text">单个数组去重</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%A4%9A%E4%B8%AA%E6%95%B0%E7%BB%84%E5%90%88%E5%B9%B6%E5%8E%BB%E9%87%8D"><span class="nav-number">3.3.</span> <span class="nav-text">多个数组合并去重</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E8%8E%B7%E5%8F%96%E4%BA%A4%E9%9B%86-%E9%87%8D%E5%A4%8D%E7%9A%84%E5%85%83%E7%B4%A0"><span class="nav-number">3.4.</span> <span class="nav-text">获取交集(重复的元素)</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%88%A4%E6%96%AD%E6%98%AF%E5%90%A6%E6%9C%89%E4%BA%A4%E9%9B%86-%E9%87%8D%E5%A4%8D%E7%9A%84%E5%85%83%E7%B4%A0"><span class="nav-number">3.5.</span> <span class="nav-text">判断是否有交集(重复的元素)</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E8%8E%B7%E5%8F%96%E5%B7%AE%E9%9B%86%EF%BC%9A%E5%8F%AA%E8%BF%94%E5%9B%9E%E9%87%8D%E5%A4%8D"><span class="nav-number">3.6.</span> <span class="nav-text">获取差集：只返回重复</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#WeakSet%E2%80%9C%E5%BC%B1%E2%80%9D%E5%9C%A8%E5%93%AA%E9%87%8C%EF%BC%9F"><span class="nav-number">4.</span> <span class="nav-text">WeakSet“弱”在哪里？</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%BC%B1%E5%8A%9F%E8%83%BD"><span class="nav-number">4.1.</span> <span class="nav-text">弱功能</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%BC%B1%E5%BC%95%E7%94%A8"><span class="nav-number">4.2.</span> <span class="nav-text">弱引用</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Reference"><span class="nav-number">5.</span> <span class="nav-text">Reference</span></a></li></ol></div>
        </section>
        <!--/noindex-->

        <section class="site-overview-wrap sidebar-panel">
          <div class="site-author site-overview-item animated" itemprop="author" itemscope itemtype="http://schema.org/Person">
  <p class="site-author-name" itemprop="name">William Leung</p>
  <div class="site-description" itemprop="description"></div>
</div>
<div class="site-state-wrap site-overview-item animated">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/murmur/archives">
          <span class="site-state-item-count">43</span>
          <span class="site-state-item-name">文章</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/murmur/categories/">
          
        <span class="site-state-item-count">9</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/murmur/tags/">
        <span class="site-state-item-count">1</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>



        </section>
      </div>
    </div>
  </aside>
  <div class="sidebar-dimmer"></div>


    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>

<noscript>
  <div class="noscript-warning">Theme NexT works best with JavaScript enabled</div>
</noscript>


    <div class="main-inner post posts-expand">
      

      

  


<div class="post-block">
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="https://gitee.com/lianghuilin/murmur.git/ecma_script/ES6%20%E8%AF%A6%E8%A7%A3Set%E5%92%8CWeakSet%E9%9B%86%E5%90%88/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/murmur/images/avatar.gif">
      <meta itemprop="name" content="William Leung">
      <meta itemprop="description" content="">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="汇话板">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          ES6 详解Set和WeakSet集合
        </h1>

        <div class="post-meta-container">
          <div class="post-meta">
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar"></i>
      </span>
      <span class="post-meta-item-text">发表于</span>

      <time title="创建时间：2021-07-04 20:30:12" itemprop="dateCreated datePublished" datetime="2021-07-04T20:30:12+08:00">2021-07-04</time>
    </span>
      <span class="post-meta-item">
        <span class="post-meta-item-icon">
          <i class="far fa-calendar-check"></i>
        </span>
        <span class="post-meta-item-text">更新于</span>
        <time title="修改时间：2021-11-28 19:00:26" itemprop="dateModified" datetime="2021-11-28T19:00:26+08:00">2021-11-28</time>
      </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-folder"></i>
      </span>
      <span class="post-meta-item-text">分类于</span>
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/murmur/categories/ECMAScript%E6%89%8B%E6%9C%AD/" itemprop="url" rel="index"><span itemprop="name">ECMAScript手札</span></a>
        </span>
    </span>

  
    <span class="post-meta-item" title="本文字数">
      <span class="post-meta-item-icon">
        <i class="far fa-file-word"></i>
      </span>
      <span class="post-meta-item-text">本文字数：</span>
      <span>5.7k</span>
    </span>
    <span class="post-meta-item" title="阅读时长">
      <span class="post-meta-item-icon">
        <i class="far fa-clock"></i>
      </span>
      <span class="post-meta-item-text">阅读时长 &asymp;</span>
      <span>5 分钟</span>
    </span>
</div>

            <div class="post-description">除了Map，就是用Array存数据，老是要去重怎么办？</div>
        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">
        <h2 id="Set是值永不重复的特殊集合"><a href="#Set是值永不重复的特殊集合" class="headerlink" title="Set是值永不重复的特殊集合"></a>Set是值永不重复的特殊集合</h2><p>每天都用数组，有没有过一个Moment，担心插入了重复的值？使用Set集合吧！Set拥有特殊的数据结构，保证插入的值永远不会重复。</p>
<h2 id="Set集合基础API"><a href="#Set集合基础API" class="headerlink" title="Set集合基础API"></a>Set集合基础API</h2><h3 id="Set-prototype-constructor-构造函数创建实例"><a href="#Set-prototype-constructor-构造函数创建实例" class="headerlink" title="Set.prototype.constructor 构造函数创建实例"></a><code>Set.prototype.constructor</code> 构造函数创建实例</h3><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/*</span></span><br><span class="line"><span class="comment"> * 仅实例化：调用构造函数，不传参数</span></span><br><span class="line"><span class="comment"> */</span> </span><br><span class="line"><span class="keyword">let</span> empty_set = <span class="keyword">new</span> <span class="built_in">Set</span>()    </span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment">/*</span></span><br><span class="line"><span class="comment"> * 实例化同时初始化：传入任意iterate对象，将其转换成Set集合</span></span><br><span class="line"><span class="comment"> */</span> </span><br><span class="line"><span class="keyword">let</span> transfer_set4arr = <span class="keyword">new</span> <span class="built_in">Set</span>([<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>])</span><br><span class="line"><span class="comment">// 返回Set(3) &#123;1, 2, 3&#125;</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">let</span> transfer_set4string = <span class="keyword">new</span> <span class="built_in">Set</span>(<span class="string">&quot;huilin&quot;</span>)</span><br><span class="line"><span class="comment">// 返回Set(5) &#123;&quot;h&quot;, &quot;u&quot;, &quot;i&quot;, &quot;l&quot;, &quot;n&quot;&#125;</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">let</span> transfer_set4set = <span class="keyword">new</span> <span class="built_in">Set</span>(<span class="keyword">new</span> <span class="built_in">Set</span>([<span class="number">5</span>, <span class="number">6</span>]))</span><br><span class="line"><span class="comment">// 返回Set(2) &#123; 5, 6 &#125;</span></span><br></pre></td></tr></table></figure>

<h3 id="Set-prototype-size属性返回元素的个数"><a href="#Set-prototype-size属性返回元素的个数" class="headerlink" title="Set.prototype.size属性返回元素的个数"></a><code>Set.prototype.size</code>属性返回元素的个数</h3><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">console</span>.log(empty_set.size) <span class="comment">// 0</span></span><br><span class="line"><span class="built_in">console</span>.log(transfer_set4arr.size)  <span class="comment">// 3</span></span><br></pre></td></tr></table></figure>

<h3 id="Set-prototype-has-value-方法判断元素是否存在"><a href="#Set-prototype-has-value-方法判断元素是否存在" class="headerlink" title="Set.prototype.has(value) 方法判断元素是否存在"></a><code>Set.prototype.has(value)</code> 方法判断元素是否存在</h3><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line"><span class="comment">// 相比起Array.includes()，Set.has()性能更高，因为专门对成员测试进行了优化</span></span><br><span class="line"><span class="built_in">console</span>.log(empty_set.has(<span class="number">1</span>))   <span class="comment">// false</span></span><br><span class="line"><span class="built_in">console</span>.log(transfer_set4arr.has(<span class="string">&#x27;h&#x27;</span>)) <span class="comment">// true</span></span><br></pre></td></tr></table></figure>

<h3 id="关于唯一值的判断"><a href="#关于唯一值的判断" class="headerlink" title="关于唯一值的判断"></a>关于唯一值的判断</h3><ul>
<li>Set集合为确保值的唯一性，使用<code>Object.is(value1,value2)</code>进行判断，而不是通过<code>===(恒等符号)</code>符号来判断的，因为恒等判断会将两边的变量进行强制类型转换。</li>
<li>比如，两个变量的值均为<code>NaN</code>，或者<code>0</code>和<code>-0</code>，用JS判断是不相等的，但<code>Object.is()</code>认为是同一个只，因此不能存入Set集合中。</li>
</ul>
<blockquote>
<p>想了解更多关于<code>Object.is()</code>，请跳转查看：<a target="_blank" rel="noopener" href="https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Object/is">https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Object/is</a></p>
</blockquote>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> n1 = <span class="literal">NaN</span></span><br><span class="line"><span class="keyword">let</span> n2 = <span class="literal">NaN</span></span><br><span class="line"></span><br><span class="line"><span class="built_in">console</span>.log(n1 === n2)  </span><br><span class="line"><span class="comment">// 恒等符号判断两者不一致，输出false</span></span><br><span class="line"></span><br><span class="line"><span class="built_in">console</span>.log(<span class="built_in">Object</span>.is(n1,n2)) </span><br><span class="line"><span class="comment">// 但Object.is()判断两者是相同的，输出false</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// Set集合不允许将两个NaN放入集合</span></span><br><span class="line"><span class="keyword">let</span> set = <span class="keyword">new</span> <span class="built_in">Set</span>()</span><br><span class="line">set.add(n1).add(n2)</span><br><span class="line"><span class="built_in">console</span>.log(set.size)   </span><br><span class="line"><span class="comment">// size: 1</span></span><br></pre></td></tr></table></figure>

<p>而面对复杂数据类型时，主要通过对象的引用进行判断。引用不一致，即便数据结构一致，也认为只不相同，因此能存入Set集合。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> same_value_set = <span class="keyword">new</span> <span class="built_in">Set</span>();</span><br><span class="line"><span class="comment">// 先存入一个对象</span></span><br><span class="line">same_value_set.add(&#123;<span class="attr">num</span>: <span class="number">0</span>&#125;);</span><br><span class="line"><span class="comment">// 再存入一个结构一致的新对象</span></span><br><span class="line"><span class="keyword">let</span> obj = &#123;<span class="attr">num</span>: <span class="number">0</span>&#125;;</span><br><span class="line">same_value_set.add(obj);</span><br><span class="line"><span class="comment">// 都能存入成功</span></span><br><span class="line"><span class="built_in">console</span>.log(same_value_set.size); <span class="comment">// 2</span></span><br></pre></td></tr></table></figure>

<h3 id="调用Set-prototype-add-value-方法，向集合追加数据"><a href="#调用Set-prototype-add-value-方法，向集合追加数据" class="headerlink" title="调用Set.prototype.add(value) 方法，向集合追加数据"></a>调用<code>Set.prototype.add(value)</code> 方法，向集合追加数据</h3><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// add()方法可以追加任意类型的数据，不论是原始值或者是对象引用</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">let</span> set1 = <span class="keyword">new</span> <span class="built_in">Set</span>()</span><br><span class="line"><span class="comment">// 由于add()方法始终返回当前实例的引用，所以进行链式调用</span></span><br><span class="line">set1.add(<span class="number">1</span>).add(<span class="number">2</span>).add(<span class="number">3</span>)</span><br><span class="line"><span class="built_in">console</span>.log(set1) <span class="comment">// Set(3) &#123;1, 2, 3&#125;</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// 注意：当add()传入数组时，Set会将数组实例插入集合，而不是数组内的元素</span></span><br><span class="line">set1.add([<span class="number">4</span>, <span class="number">5</span>])</span><br><span class="line"><span class="built_in">console</span>.log(set1) <span class="comment">// Set(4) &#123;1, 2, 3, [4, 5]&#125;</span></span><br></pre></td></tr></table></figure>

<h3 id="Set-prototype-delete-value-方法移除元素"><a href="#Set-prototype-delete-value-方法移除元素" class="headerlink" title="Set.prototype.delete(value) 方法移除元素"></a><code>Set.prototype.delete(value)</code> 方法移除元素</h3><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// delete()方法返回移除操作是否成功，与.has()方法一样</span></span><br><span class="line"><span class="keyword">let</span> success = set1.delete(<span class="number">1</span>)</span><br><span class="line"><span class="built_in">console</span>.log(success)</span><br><span class="line"><span class="comment">// true</span></span><br></pre></td></tr></table></figure>

<h3 id="Set-prototype-clear-方法清空集合"><a href="#Set-prototype-clear-方法清空集合" class="headerlink" title="Set.prototype.clear() 方法清空集合"></a><code>Set.prototype.clear()</code> 方法清空集合</h3><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> num_set = <span class="keyword">new</span> <span class="built_in">Set</span>([<span class="number">1</span>, <span class="number">6</span>, <span class="number">3</span>])</span><br><span class="line"><span class="built_in">console</span>.log(num_set)</span><br><span class="line"><span class="comment">// Set(3) &#123; 1, 6, 3 &#125;</span></span><br><span class="line"></span><br><span class="line">set1.clear()</span><br><span class="line"><span class="built_in">console</span>.log(num_set)</span><br><span class="line"><span class="comment">// Set(0) &#123;&#125;</span></span><br></pre></td></tr></table></figure>

<h3 id="Set集合遍历的3种方式"><a href="#Set集合遍历的3种方式" class="headerlink" title="Set集合遍历的3种方式"></a>Set集合遍历的3种方式</h3><ul>
<li>由于集合没有下标/索引，通常被认为是“无序集合”。但JavaScript会记住元素插入的顺序，所以遍历的时候也按顺序对元素进行迭代。</li>
</ul>
<ol>
<li>直接遍历Set集合</li>
</ol>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> set = <span class="keyword">new</span> <span class="built_in">Set</span>([<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>, <span class="number">4</span>, <span class="number">5</span>])</span><br><span class="line"><span class="keyword">for</span>(<span class="keyword">let</span> item <span class="keyword">of</span> set)&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(item)</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">// 依次输出：1 2 3 4 5</span></span><br></pre></td></tr></table></figure>

<ol start="2">
<li>创建迭代器进行遍历</li>
</ol>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/*</span></span><br><span class="line"><span class="comment"> * 创建迭代器的有三种方式</span></span><br><span class="line"><span class="comment"> * Set.prototype.entries()</span></span><br><span class="line"><span class="comment"> * Set.prototype.keys()</span></span><br><span class="line"><span class="comment"> * Set.prototype.values()</span></span><br><span class="line"><span class="comment"> */</span> </span><br><span class="line"></span><br><span class="line"><span class="comment">// Set集合只有value而没有key，但为了使得和遍历Map对象相似，Set.entries()创建新的Iterator对象时，每一项的键和值都相等，即[value,value]</span></span><br><span class="line"><span class="keyword">for</span>(<span class="keyword">let</span> [key,value] <span class="keyword">of</span> set.entries())&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(value)</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">// 依次输出：1 2 3 4 5</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// Set.keys()创建新的Iterator对象，返回每一项值</span></span><br><span class="line"><span class="keyword">for</span>(<span class="keyword">let</span> key <span class="keyword">of</span> set.keys())&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(key)</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">// 依次输出：1 2 3 4 5</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// Set.values()和Set.keys()一致，返回每一项的值</span></span><br><span class="line"><span class="keyword">for</span>(<span class="keyword">let</span> value <span class="keyword">of</span> set.values())&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(value)</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">// 依次输出：1 2 3 4 5</span></span><br></pre></td></tr></table></figure>

<ol start="3">
<li>调用<code>Set.prototype.forEach(callbackFn)</code>方法遍历</li>
</ol>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// forEach(callbackFn) 按照插入顺序调用callbackFn，取出每项值</span></span><br><span class="line">set.forEach(<span class="function"><span class="params">item</span> =&gt;</span> &#123;</span><br><span class="line">    <span class="built_in">console</span>.log(item)</span><br><span class="line">&#125;)</span><br><span class="line"><span class="comment">// 依次输出：1 2 3 4 5</span></span><br></pre></td></tr></table></figure>

<h2 id="Set集合案例实践"><a href="#Set集合案例实践" class="headerlink" title="Set集合案例实践"></a>Set集合案例实践</h2><h3 id="Set集合与Array数组之间的转换"><a href="#Set集合与Array数组之间的转换" class="headerlink" title="Set集合与Array数组之间的转换"></a>Set集合与Array数组之间的转换</h3><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/*</span></span><br><span class="line"><span class="comment"> * Set转Array</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">let</span> set1 = <span class="keyword">new</span> <span class="built_in">Set</span>([<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>])</span><br><span class="line"><span class="comment">// Array.from()方法</span></span><br><span class="line"><span class="keyword">let</span> arr1 = <span class="built_in">Array</span>.from(set1)  </span><br><span class="line"><span class="comment">// 扩展运算符</span></span><br><span class="line"><span class="keyword">let</span> arr2 = [...set1]  </span><br><span class="line"></span><br><span class="line"><span class="comment">/*</span></span><br><span class="line"><span class="comment"> * Array转Set</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"> <span class="comment">// 利用Set构造函数</span></span><br><span class="line"><span class="keyword">let</span> set = <span class="keyword">new</span> <span class="built_in">Set</span>(array)</span><br></pre></td></tr></table></figure>

<h3 id="单个数组去重"><a href="#单个数组去重" class="headerlink" title="单个数组去重"></a>单个数组去重</h3><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> set = <span class="keyword">new</span> <span class="built_in">Set</span>([<span class="number">1</span>, <span class="number">2</span>, <span class="number">4</span>, <span class="number">4</span>, <span class="number">2</span>, <span class="number">5</span>])</span><br><span class="line"><span class="built_in">console</span>.log(set)</span><br><span class="line"><span class="comment">// Set(4) &#123; 1, 2, 4, 5 &#125;</span></span><br></pre></td></tr></table></figure>

<h3 id="多个数组合并去重"><a href="#多个数组合并去重" class="headerlink" title="多个数组合并去重"></a>多个数组合并去重</h3><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> arr1 = [<span class="number">1</span>, <span class="number">2</span>, <span class="number">4</span>]</span><br><span class="line"><span class="keyword">let</span> arr2 = [<span class="number">1</span>, <span class="number">5</span>, <span class="number">6</span>]</span><br><span class="line"></span><br><span class="line"><span class="comment">// 利用Set集合的特性，集合内的元素都是唯一的</span></span><br><span class="line"><span class="keyword">let</span> result = <span class="keyword">new</span> <span class="built_in">Set</span>([...set1, ...set2]) </span><br><span class="line"><span class="built_in">console</span>.log(result)</span><br><span class="line"><span class="comment">// Set(5) &#123; 1, 2, 4, 5, 6 &#125;</span></span><br></pre></td></tr></table></figure>

<h3 id="获取交集-重复的元素"><a href="#获取交集-重复的元素" class="headerlink" title="获取交集(重复的元素)"></a>获取交集(重复的元素)</h3><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> set1 = <span class="keyword">new</span> <span class="built_in">Set</span>([<span class="number">1</span>, <span class="number">2</span>, <span class="number">4</span>])</span><br><span class="line"><span class="keyword">let</span> set2 = <span class="keyword">new</span> <span class="built_in">Set</span>([<span class="number">1</span>, <span class="number">5</span>, <span class="number">6</span>])</span><br><span class="line"></span><br><span class="line"><span class="comment">// 返回set1和set2都存在的元素</span></span><br><span class="line"><span class="keyword">let</span> result = <span class="keyword">new</span> <span class="built_in">Set</span>([...set1].filter(<span class="function"><span class="params">x</span> =&gt;</span> set2.has(x))) </span><br><span class="line"><span class="built_in">console</span>.log(result)</span><br><span class="line"><span class="comment">// Set(1) &#123; 1 &#125;</span></span><br></pre></td></tr></table></figure>

<h3 id="判断是否有交集-重复的元素"><a href="#判断是否有交集-重复的元素" class="headerlink" title="判断是否有交集(重复的元素)"></a>判断是否有交集(重复的元素)</h3><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> set1 = <span class="keyword">new</span> <span class="built_in">Set</span>([<span class="number">1</span>, <span class="number">2</span>, <span class="number">4</span>])</span><br><span class="line"><span class="keyword">let</span> set2 = <span class="keyword">new</span> <span class="built_in">Set</span>([<span class="number">1</span>, <span class="number">5</span>, <span class="number">6</span>])</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">isMixed</span>(<span class="params">set, subset</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">let</span> elem <span class="keyword">of</span> subset) &#123;</span><br><span class="line">        <span class="keyword">if</span> (set.has(elem)) &#123;</span><br><span class="line">            <span class="keyword">return</span> <span class="literal">true</span>;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> <span class="literal">false</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="built_in">console</span>.log(isMixed(set1, set2))</span><br><span class="line"><span class="comment">// true</span></span><br></pre></td></tr></table></figure>

<h3 id="获取差集：只返回重复"><a href="#获取差集：只返回重复" class="headerlink" title="获取差集：只返回重复"></a>获取差集：只返回重复</h3><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> set1 = <span class="keyword">new</span> <span class="built_in">Set</span>([<span class="number">1</span>, <span class="number">2</span>, <span class="number">4</span>])</span><br><span class="line"><span class="keyword">let</span> set2 = <span class="keyword">new</span> <span class="built_in">Set</span>([<span class="number">1</span>, <span class="number">5</span>, <span class="number">6</span>])</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">difference</span>(<span class="params">setA, setB</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">let</span> result = <span class="keyword">new</span> <span class="built_in">Set</span>()</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">let</span> elem <span class="keyword">of</span> setB) &#123;</span><br><span class="line">        <span class="keyword">if</span>(setA.has(elem))&#123;</span><br><span class="line">            result.add(elem)</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> result;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="built_in">console</span>.log(difference(set1, set2))</span><br></pre></td></tr></table></figure>

<h2 id="WeakSet“弱”在哪里？"><a href="#WeakSet“弱”在哪里？" class="headerlink" title="WeakSet“弱”在哪里？"></a>WeakSet“弱”在哪里？</h2><p>除了Set集合外，ES6还提供了WeakSet和WeakMap。既然集合的名字都叫“Weak(弱)的集合”了，究竟它“弱”在哪里呢？</p>
<h3 id="弱功能"><a href="#弱功能" class="headerlink" title="弱功能"></a>弱功能</h3><ul>
<li>WeakSet不允许插入原始值，仅支持对象的引用；</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> val1 = &#123;<span class="attr">id</span>: <span class="number">1</span>&#125;,</span><br><span class="line">    val2 = &#123;<span class="attr">id</span>: <span class="number">2</span>&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">let</span> ws = <span class="keyword">new</span> <span class="built_in">WeakSet</span>()</span><br><span class="line"></span><br><span class="line"><span class="comment">// 和Set集合一样，WeakSet的值也不重复，同时add()也返回集合实例，所以可以链式操作</span></span><br><span class="line">ws.add(val1).add(val1).add(val2)</span><br><span class="line"></span><br><span class="line"><span class="comment">// 不允许插入基础数据类型</span></span><br><span class="line">ws.add(<span class="number">3</span>)</span><br><span class="line"><span class="comment">// 报错：TypeError：Invalid value used in WeakSet</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// 但可以先包装成对象后再插入</span></span><br><span class="line"><span class="keyword">let</span> val3 = <span class="keyword">new</span> <span class="built_in">Number</span>(<span class="number">3</span>)</span><br><span class="line">ws.add(val3)</span><br><span class="line"><span class="built_in">console</span>.log(ws.has(val3))</span><br><span class="line"><span class="comment">// 输出：true</span></span><br><span class="line"></span><br></pre></td></tr></table></figure>

<ul>
<li>WeakSet仅实现了<code>add()</code>、<code>has()</code>、<code>delete()</code>三个操作方法；</li>
<li>WeakSet不允许遍历，也没有size或者length属性；</li>
</ul>
<h3 id="弱引用"><a href="#弱引用" class="headerlink" title="弱引用"></a>弱引用</h3><p>要说弱引用，先看看什么是强引用：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 声明一个对象</span></span><br><span class="line"><span class="keyword">let</span> handsome = &#123;</span><br><span class="line">    name: <span class="string">&#x27;huilin&#x27;</span>,</span><br><span class="line">    age: <span class="number">30</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 放入数组</span></span><br><span class="line"><span class="keyword">let</span> arr = [<span class="number">1</span>, handsome, <span class="number">2</span>]</span><br><span class="line"><span class="built_in">console</span>.log(<span class="string">&#x27;release before arr length&#x27;</span>, arr.length) <span class="comment">// 3</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// 放入Map</span></span><br><span class="line"><span class="keyword">let</span> user = &#123;</span><br><span class="line">    oid: <span class="number">10001</span>,</span><br><span class="line">    classify: <span class="string">&#x27;Chinese&#x27;</span>,</span><br><span class="line">    staffReference: handsome</span><br><span class="line">&#125;</span><br><span class="line"><span class="built_in">console</span>.log(<span class="string">&#x27;release before map length&#x27;</span>, <span class="built_in">Object</span>.keys(user).length) <span class="comment">// 3</span></span><br><span class="line"></span><br><span class="line"><span class="built_in">console</span>.log(<span class="string">&#x27;----&#x27;</span>)</span><br><span class="line"></span><br><span class="line"><span class="comment">// 突然把对象置为null</span></span><br><span class="line">handsome = <span class="literal">null</span></span><br><span class="line"><span class="comment">// 强引用的容器中，对象仍然存在没有被回收</span></span><br><span class="line"><span class="built_in">console</span>.log(<span class="string">&#x27;release after arr length&#x27;</span>, arr.length) <span class="comment">// 3</span></span><br><span class="line"><span class="built_in">console</span>.log(arr[<span class="number">1</span>]) <span class="comment">// &#123; name: &#x27;huilin&#x27;, age: 30 &#125;</span></span><br><span class="line"><span class="built_in">console</span>.log(<span class="string">&#x27;release after map length&#x27;</span>, <span class="built_in">Object</span>.keys(user).length) <span class="comment">// 3</span></span><br><span class="line"><span class="built_in">console</span>.log(user.staffReference) <span class="comment">// &#123; name: &#x27;huilin&#x27;, age: 30 &#125;</span></span><br></pre></td></tr></table></figure>

<p>从测试代码看出，除非容器销毁，否则引用的对象一直没有被回收。而所谓弱引用，就是希望容器是根据元素自动伸缩的，一旦对象为null，容器中的引用也跟着回收。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> obj1 = &#123;</span><br><span class="line">    name: <span class="string">&#x27;huilin&#x27;</span>,</span><br><span class="line">    age: <span class="number">30</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">let</span> obj2 = &#123;</span><br><span class="line">    name: <span class="string">&#x27;cc&#x27;</span>,</span><br><span class="line">    age: <span class="number">29</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">let</span> ws1 = <span class="keyword">new</span> <span class="built_in">WeakSet</span>()</span><br><span class="line">ws1.add(obj1).add(obj2)</span><br><span class="line"><span class="built_in">console</span>.log(ws1.has(obj1))  <span class="comment">// true</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// 不管是从容器操作元素</span></span><br><span class="line">ws1.delete(obj1)</span><br><span class="line"><span class="built_in">console</span>.log(ws1.has(obj1))  <span class="comment">// false</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// 或者是对象自己置为null，都会自动回收</span></span><br><span class="line">obj2 = <span class="literal">null</span></span><br><span class="line"><span class="built_in">console</span>.log(ws1.has(obj2))  <span class="comment">// false</span></span><br></pre></td></tr></table></figure>

<h2 id="Reference"><a href="#Reference" class="headerlink" title="Reference"></a>Reference</h2><ul>
<li><a target="_blank" rel="noopener" href="https://zh.javascript.info/map-set">https://zh.javascript.info/map-set</a></li>
<li><a target="_blank" rel="noopener" href="https://es6.ruanyifeng.com/#docs/set-map">https://es6.ruanyifeng.com/#docs/set-map</a></li>
</ul>

    </div>

    
    
    

    <footer class="post-footer">
          

<div class="post-copyright">
<ul>
  <li class="post-copyright-author">
      <strong>本文作者： </strong>William Leung
  </li>
  <li class="post-copyright-link">
      <strong>本文链接：</strong>
      <a href="https://gitee.com/lianghuilin/murmur.git/ecma_script/ES6%20%E8%AF%A6%E8%A7%A3Set%E5%92%8CWeakSet%E9%9B%86%E5%90%88/" title="ES6 详解Set和WeakSet集合">https://gitee.com/lianghuilin/murmur.git/ecma_script/ES6 详解Set和WeakSet集合/</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" rel="noopener" target="_blank"><i class="fab fa-fw fa-creative-commons"></i>BY-NC-SA</a> 许可协议。转载请注明出处！
  </li>
</ul>
</div>


        

          <div class="post-nav">
            <div class="post-nav-item">
                <a href="/murmur/vue3_practice/Vue3%E4%B8%ADref%E6%A8%A1%E6%9D%BF%E5%BC%95%E7%94%A8%E7%9A%84%E7%90%86%E8%A7%A3%E4%B8%8E%E5%AE%9E%E8%B7%B5/" rel="prev" title="Vue3中ref模板引用的理解与实践">
                  <i class="fa fa-chevron-left"></i> Vue3中ref模板引用的理解与实践
                </a>
            </div>
            <div class="post-nav-item">
                <a href="/murmur/echarts/ECharts%E5%AE%9E%E7%8E%B0%E7%8E%AF%E5%9B%BE%E8%BD%AE%E6%92%AD%E4%BB%A5%E5%8F%8A%E4%BA%8B%E4%BB%B6%E6%8E%A7%E5%88%B6/" rel="next" title="ECharts实现环图轮播以及事件控制">
                  ECharts实现环图轮播以及事件控制 <i class="fa fa-chevron-right"></i>
                </a>
            </div>
          </div>
    </footer>
  </article>
</div>






      

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      const activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      const commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

    </div>
  </main>

  <footer class="footer">
    <div class="footer-inner">
      

      

<div class="copyright">
  
  &copy; 
  <span itemprop="copyrightYear">2023</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">William Leung</span>
</div>
<div class="wordcount">
  <span class="post-meta-item">
    <span class="post-meta-item-icon">
      <i class="fa fa-chart-line"></i>
    </span>
    <span title="站点总字数">142k</span>
  </span>
  <span class="post-meta-item">
    <span class="post-meta-item-icon">
      <i class="fa fa-coffee"></i>
    </span>
    <span title="站点阅读时长">2:09</span>
  </span>
</div>
<div class="busuanzi-count">
    <span id="busuanzi_container_site_uv">
      本站访客数<span id="busuanzi_value_site_uv"></span>人次
    </span>
    <span id="busuanzi_container_site_pv">
        本站总访问量<span id="busuanzi_value_site_pv"></span>次
    </span>
</div>
  <div class="powered-by">由 <a href="https://hexo.io/" class="theme-link" rel="noopener" target="_blank">Hexo</a> & <a href="https://theme-next.js.org/" class="theme-link" rel="noopener" target="_blank">NexT.Gemini</a> 强力驱动
  </div>

    </div>
  </footer>

  
  <script src="//cdn.jsdelivr.net/npm/animejs@3.2.1/lib/anime.min.js"></script>
<script src="/murmur/js/utils.js"></script><script src="/murmur/js/motion.js"></script><script src="/murmur/js/next-boot.js"></script>

  
















  <script>
    NProgress.configure({
      showSpinner: true
    });
    NProgress.start();
    document.addEventListener('readystatechange', () => {
      if (document.readyState === 'interactive') {
        NProgress.inc(0.8);
      }
      if (document.readyState === 'complete') {
        NProgress.done();
      }
    });
    document.addEventListener('pjax:send', () => {
      NProgress.start();
    });
    document.addEventListener('pjax:success', () => {
      NProgress.done();
    });
  </script>


  
  <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>








  

  

</body>
</html>
